
import 'package:baselib/utils/keyboard_util.dart';
import 'package:baselib/utils/load_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/md5_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:baselib/utils/toast_util.dart';
import 'package:baselib/widgets/dialog_util.dart';
import 'package:baselib/widgets/refresh_util.dart';
import 'package:framelib/base/base_view_model.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/config/route_config.dart';
import 'package:framelib/net/baseentity.dart';
import 'package:framelib/utils/nim_sdk_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/page_widget.dart';
import 'package:get/state_manager.dart';
import 'package:get/get.dart';
import 'package:module_business/module_chat/service/module_chat_service.dart';
import 'package:module_business/module_comm/model/user_entity.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_comm/service/module_comm_service.dart';
import 'package:module_business/module_index/model/index_room_item_entity.dart';
import 'package:module_business/module_index/service/module_index_service.dart';
import 'package:module_business/module_index/view/create_voice_room_widget.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:nim_core/nim_core.dart';

class MessageViewModel extends BaseViewModel<ModuleChatService>{

  ModuleChatService moduleChatService;
  ModuleIndexService moduleIndexService;
  RefreshController refreshController = RefreshController(initialRefresh: true);
  RefreshState loadStatus=RefreshState.OK;
  int page = 1;
  bool isCanMoreData = false;
  List<NIMSession> dataLists=[];
  //自己创建的房间
  IndexRoomItemEntity myRoomItemEntity=IndexRoomItemEntity();
  List<String> msgPersonIds = [];
  List<UserEntity> msgPersons = [];

  @override
  ModuleChatService createService(){
    moduleIndexService = ModuleIndexService();
    return moduleChatService = ModuleChatService();
  }
  @override
  void onInit() {
    super.onInit();
    //设置监听
    setLisener();
    //查询我的房间
    getMyRoom();
  }
  setLisener() async{
    await NimCore.instance.messageService.onSessionUpdate.listen((List<NIMSession> sessions) {
      LogUtil.d('ChatViewModel--->onSessionUpdate');
      onRefresh(pageCur: 1);
    });
  }
  onRefresh({int pageCur,}) async{
    if(pageCur!=null)page=pageCur;
    // Map<String,dynamic> upData={
    //   'searchValue':voiceChatTag?.id,
    // };
    // BaseEntity baseEntity= await moduleIndexService
    //     .api_voicechat_room_findRoomListByTag(parmsMap: upData);
    NIMResult<List<NIMSession>> result = await NimCore.instance.messageService.querySessionList();
    if(refreshController!=null)refreshController.refreshCompleted();
    if(refreshController!=null)refreshController.loadComplete();
    if(result?.isSuccess??false){
      loadStatus=RefreshState.OK;
      List<NIMSession> sessionLists = result?.data??[];
      if(sessionLists.isNotEmpty){
        dataLists = sessionLists;
        LogUtil.d('MessageViewModel--->dataLists=${dataLists.map((e) => e?.toMap())?.toList()}');
        var senderAccounts = dataLists.map((e) => e?.sessionId).toList();
        msgPersonIds.addAll(senderAccounts);
        //去重
        Set<String> chatRoomMemberIdsSets = new Set();
        chatRoomMemberIdsSets.addAll(msgPersonIds);
        msgPersonIds = chatRoomMemberIdsSets.toList();
        _getChatServiceMembers();
      }
    }else{
      loadStatus=RefreshState.EMPTY;
    }
    update();
  }
  void getMyRoom() async{
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_queryMyRoom(parmsMap: {});
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      IndexRoomItemEntity results = baseEntity.result;
      if(results!=null){
        myRoomItemEntity = results;
        UserParamsModel.instance.setMyRoom(myRoomItemEntity);
        update();
      }
    }
  }

  voiceRoomAdd() {
    if(myRoomItemEntity?.id==null){
      //添加房间
      DialogUtil.instance.showCommBottomSheet(
          child: CreateVoiceRoomWidget(
              onClose: ()=>NavigatorUtil.goBack(),
              onStart: (coverPath,roomName,roomPassword,roomTagId,roomRemark,isSetPassword){
                LogUtil.d('voiceRoomAdd-->coverPath=$coverPath\n,roomName=$roomName\n,'
                    'roomPassword=$roomPassword\n,roomTagId=$roomTagId\n,roomRemark=$roomRemark\n,isSetPassword=$isSetPassword');
                NavigatorUtil.goBack();
                //开始提交创建房间
                createRoom(coverPath,roomName,roomPassword,roomTagId,roomRemark,isSetPassword);
              }
          )
      );
    }else{
      //去我的房间
      toMyRoom();
    }
  }

  void createRoom(coverPath, roomName, roomPassword, roomTagId, roomRemark,isSetPassword) async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.Creating);
    Map<String,dynamic> upData={
      'coverImg': coverPath,
      'password': (isSetPassword??false)?roomPassword:'',
      'roomName': roomName,
      'roomSynopsis': roomRemark,
      'tagId': roomTagId,
    };
    LogUtil.d('createRoom--->upData=$upData');
    // {coverImg: https://app-bucket-test.oss-accelerate.aliyuncs.com/ios/77985415/230314/u10233294541678777215792(960x1280).jpg, password: , roomName: tianqihao, roomSynopsis: nfjksansanjfs, tagId: 28}

    LoadUtil.hideLoad();
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_createRoom(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      ToastUtil.toast(StringUtil.instance.Create_success);
      //查询我的房间
      getMyRoom();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }
  void toMyRoom() async{
    //api_voicechat_room_joinRoom
    LoadUtil.showLoad(loadingText: StringUtil.instance.data_loading);
    Map<String,dynamic> upData={
      'id': myRoomItemEntity?.id,
      'password': myRoomItemEntity?.password,
    };
    LogUtil.d('toMyRoom--->upData=$upData');
    BaseEntity baseEntity = await moduleIndexService.api_voicechat_room_joinRoom(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      IndexRoomItemEntity roomItem = baseEntity?.result;
      //云信进入房间
      var  enterChatroomResult = await NIMSDKUtil.instance.enterChatroom(
          roomId: roomItem?.yxRoomId,
          nickname: UserParamsModel.instance.selfNIMUser.nick,
          avatar: UserParamsModel.instance.selfNIMUser.avatar
      );
      LoadUtil.hideLoad();
      if (enterChatroomResult.isSuccess) {
        LogUtil.d('进入聊天室成功');
        NavigatorUtil.pushByName(RouteConfig.myRoomPage,arguments: {
          'roomItem': roomItem
        });
      }else{
        LogUtil.d('进入聊天室失败');
      }
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  //获取服务端成员列表
  void _getChatServiceMembers() async{
    LogUtil.d('_getChatRoomServiceMembers--->msgPersonIds=$msgPersonIds');
    Map<String,dynamic> upData={
      "roomId": 0,
      "yxAccids": msgPersonIds
    };
    BaseEntity baseEntity= await moduleIndexService
        .api_voicechat_room_queryOnlineUserInfo(parmsMap: upData);
    if(baseEntity?.code==ApiConfig.SUCCESS_CODE){
      List<UserEntity> dataTemps=baseEntity?.result??[];
      if(dataTemps.isNotEmpty){
        msgPersons.clear();
        msgPersons.addAll(dataTemps);
        update();
      }
    }
  }
  void toChat(NIMSession sessionItem,UserEntity micMember) {
    NavigatorUtil.pushByName(RouteConfig.chatPage,arguments: {
      'voicePersonYxAccid':sessionItem?.sessionId,
      'voicePersonUserId':'${micMember?.userId}',
      'voicePersonNickName':micMember?.nickname,
      'voicePersonIcon':micMember?.icon,
    });
  }

  toSystemNotification(NIMSession tipListItem, param) {
    //systemNotificationPage
    NavigatorUtil.pushByName(RouteConfig.systemNotificationPage,arguments: {
      'voicePersonYxAccid':tipListItem?.sessionId,
    });
  }
}
